import md5 from './md5.mini'
import sendRequest from './request'

const util = {
  processDate(date) {
    if (typeof date === "string") {
      date = new Date(
        date
          .replace(/\..*$/, "")
          .replace(/-/g, "/")
          .replace(/\+/g, " ")
      );
    }
    return new Date(date);
  },
  //链接参数转换
  urlToObj(url) {
    var search = url.replace(/^\s+|\s+$/, "").match(/([^?#]*)(#.*)?$/);
    if (!search) {
      return {};
    }
    var searchHash = search[1].split("&");
    var obj = {};
    for (var i = 0, len = searchHash.length; i < len; i++) {
      var pair = searchHash[i].split("=");
      if (pair[0]) {
        var key = decodeURIComponent(pair[0]);
        var value = pair[1];
        if (pair[2]) {
          value = `${pair[1]}=${pair[2]}`;
        }
        if (value != undefined) {
          value = decodeURIComponent(value);
        }
        //这里判断转化后的obj里面有没有重复的属性
        if (key in obj) {
          if (obj[key] != Array) {
            //把属性值变为数组，将另外的属性值也存放到数组中去
            obj[key] = [obj[key]];
          }
          obj[key].push(value);
        } else {
          obj[key] = value;
        }
      }
    }
    return obj;
  }

}



/**
 * 获取服务器时间
 */
export const getServerDate = ()=>{
    return new Promise(async(resolve)=>{
        const locDate = new Date() 
        try {
            const {body} = await sendRequest('CommonActivity', {
              data: {},
              serviceName: 'serverdate',
            })
            const {serverTime} = body || {}
            const timeStamp = Date.parse(util.processDate(serverTime))
            resolve(timeStamp)
        } catch (error) {
          const locDateStamp = Date.parse(locDate)
          resolve(locDateStamp)
        }
    })
}

/**
 * 将所有参数字段按首字母排序， 拼接成key1 = value1 & key2 = value2的格式，再在末尾拼接上 timestamp=Date.now()&kAppKey = kAppKey 再做MD5加密生成sign
 * kAppKey 为常量
 * 仅业务参数参与加密,公共参数不参与加密 (platId,refid,sessionCode)
 * @param {object} params 
 * @param {string} kAppKey 
 * @returns {object} 
 * 仅业务参数参与加密,公共参数不参与加密 (platId,refid,sessionCode)
 */

export async function getSign (params, kAppKey) {
    let content;
    let paramsObj;
    const timeStamp = await getServerDate()
    if (typeof params == "string") {
        paramsObj = util.urlToObj(params)
    }else if (typeof params == "object") {
        paramsObj = params
    }
    let arr = [];
    for (let i in paramsObj) {
      if(['memberid', 'sessioncode', 'platid','refid'].indexOf(i.toLowerCase()) > -1 ){
        continue
      }
      paramsObj[i] !== '' && arr.push(i + "=" + paramsObj[i]);
    }
    content = arr.join("&")
    const url = content.split("&").sort().join("&")
    const lowerUrl = `${url}&timestamp=${timeStamp}&appKey=`.toLowerCase()
    const newUrl = `${lowerUrl}${kAppKey}`.replace(/^&/,'');
    const signValue = md5(newUrl)
    return {
      timeStamp,
      sign:signValue
    };
}
